import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hixing_app/const/gaps.dart';
import 'package:hixing_app/utils/export_utils.dart';
import 'package:nsd/nsd.dart' as nsd;

class WifiScan extends StatefulWidget {
  @override
  _WifiScanState createState() => _WifiScanState();
}

class _WifiScanState extends State<WifiScan> {
  final serviceList = <nsd.Service>[];
  final registrations = <nsd.Registration>[];
  ValueNotifier isScan = ValueNotifier(false);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose

    super.dispose();
  }

  Future<void> registerService() async {
    // 注册服务
    final registration = await nsd.register(
        const nsd.Service(name: 'Foo', type: '_http._tcp', port: 56000));

    //注销服务
    await nsd.unregister(registration);
  }

  Future<void> startScan() async {
    isScan.value = true;
    final discovery = await nsd.startDiscovery('_http._tcp',
        ipLookupType: nsd.IpLookupType.v4);
    serviceList.clear();
    discovery.addServiceListener((service, status) {
      if (status == nsd.ServiceStatus.found) {
        // put service in own collection, etc.
        print("当前可发现的服务host：${service.host}");
        serviceList.add(service);
      }
    });
    // 5s后关闭服务扫描
    await Future.delayed(Duration(seconds: 5));
    await nsd.stopDiscovery(discovery);
    setState(() {});
    isScan.value = false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('wifi 扫描'),
      ),
      body: Center(
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                startScan();
              },
              child: Text("开始扫描"),
            ),
            ListenableBuilder(
              listenable: isScan,
              builder: (ctx, child) {
                return Text("扫描状态：${isScan.value ? "扫描中" : "没有扫描"}");
              },
            ),
            Expanded(
              child: ListView.builder(
                itemCount: serviceList.length,
                itemBuilder: (ctx, index) {
                  nsd.Service data = serviceList[index];
                  return Container(
                    padding: EdgeInsets.all(20),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text("name：${data.name}"),
                        Gaps.vGap4,
                        Text("addresses：${data.addresses}"),
                        Gaps.vGap4,
                        Text("port：${data.port}"),
                        Gaps.vGap4,
                        Text("host：${data.host}"),
                        Gaps.vGap4,
                        Text("type：${data.type}"),
                        Gaps.vGap4,
                        Text("txt：${data.txt}"),
                      ],
                    ),
                  );
                },
              ),
            ),
            Gaps.getVGap(ScreenUI.bottomSafeHeight)
          ],
        ),
      ),
    );
  }
}
